using Autodesk.Revit.UI;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using RevitForge.Services;
using System;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;

namespace RevitForge.ViewModels
{
    [ObservableObject]
    public partial class ScriptBotViewModel
    {
        private readonly ExternalEvent _externalEvent;
        private readonly DeepSeekService _deepSeekService;
        [ObservableProperty]
        private bool _isInitialView = true;

        [ObservableProperty]
        private bool _isChatView = false;

        [ObservableProperty]
        private bool _isSave = false;

        [ObservableProperty]
        private bool _isLoading = false;

        [ObservableProperty]
        private string _prompt;

        [ObservableProperty]
        private string userCode;
        public ScriptBotViewModel(ExternalEvent externalEvent)
        {
            _externalEvent = externalEvent;
            // 从配置文件读取 Deepseek 密钥
            string apiKey = ApiKeySetService.GetApiKey();
            _deepSeekService = new DeepSeekService(apiKey);
        }
        [ICommand]
        private void ShowSettings()
        {
            ApiKeySetService.ShowApiKeySettings();
            // 更新 DeepSeekService 的 API 密钥
            string apiKey = ApiKeySetService.GetApiKey();
            _deepSeekService.UpdateApiKey(apiKey);
        }
        [ICommand]
        private async Task Generate(string question)
        {
            this.Prompt = "";
            try
            {
                //loading每次都要
                IsLoading = true;
                IsSave = false;
                // 隐藏欢迎界面，设置加载状态为true
                if (IsInitialView)
                {
                    IsInitialView = false;
                    IsChatView = true;
                }
                if (string.IsNullOrWhiteSpace(question))
                {
                    MessageBox.Show("请输入功能描述", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                string res = await _deepSeekService.GenerateCodeAsync(question);
                // 去除首尾空白字符
                res = res.Trim();
                // 首尾移除代码标记（如果有）
                if (res.StartsWith("```csharp") || res.StartsWith("```cs") || res.StartsWith("```"))
                {
                    res = res.Substring(res.IndexOf('\n') + 1);
                }
                if (res.EndsWith("```"))
                {
                    res = res.Substring(0, res.LastIndexOf("```")).TrimEnd();
                }
                UserCode = res;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"生成代码失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                // 无论成功还是失败，都将加载状态设置为false
                IsLoading = false;
                IsSave = true;
            }
        }
        [ICommand]
        private void Execute()
        {
            // 将用户输入的代码存储到静态变量中供 ExternalEvent 使用
            Services.ScriptExecuteHandler.UserCode = UserCode;
            // 触发外部事件，开始执行代码
            _externalEvent.Raise();
        }

        [ICommand]
        private void Save()
        {
            // 使用正则表达式获取实现了IExternalCommand接口的类名
            var match = Regex.Match(UserCode, @"class\s+(\w+Command)\b");
            if (!match.Success)
            {
                MessageBox.Show("未找到实现IExternalCommand接口的类", "保存失败", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            string className = match.Groups[1].Value;
            string fileName = className.TrimEnd("Command".ToCharArray());
            string sourceDir = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Source");

            // 确保Source目录存在
            if (!Directory.Exists(sourceDir))
            {
                Directory.CreateDirectory(sourceDir);
            }

            // 保存代码到文件
            string filePath = Path.Combine(sourceDir, $"{fileName}.txt");
            File.WriteAllText(filePath, UserCode);
            MessageBox.Show($"代码保存成功", "保存成功", MessageBoxButton.OK, MessageBoxImage.Information);
        }
        [ICommand]
        private void NewChat()
        {
            IsInitialView = true;
            IsChatView = false;
            IsSave = false;
            UserCode = string.Empty;
            Prompt = string.Empty;
            _deepSeekService.ClearHistory();
        }
    }
}
